package cn.lcfms.app.index.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.lcfms.app.admin.bean.TagBean;
import cn.lcfms.bin.App;
import cn.lcfms.service.BaseService;

@Controller("index.Tag")
@RequestMapping("/index/tag")
public class Tag extends BaseController{
	/*
	 * 首页
	 */
	@RequestMapping("/init")
	public String init(HttpServletRequest request){	
		request.setAttribute("ui", "Bootstrap UI");
		return "tag/ui";
	}
	/*
	 * 测试分页
	 */
	@RequestMapping("/page")
	public String page(HttpServletRequest request,int pageNumber){	
		setTagStatics(request);
		request.setAttribute("pageNumber", pageNumber);
		return "tag/conta-table-temp";
	}
	/*
	 * 模拟上传文件后的处理
	 */
	@ResponseBody
	@RequestMapping("/uploadfile")
	public String uploadfile(HttpServletResponse response){
		JSONObject json=JSONObject.fromObject("{filePath:'123.jpg'}");		
		return json.toString();
	}
	/*
	 * 个人介绍页面
	 */
	@RequestMapping("/hello")
	public String hello(HttpServletRequest request){	
		setTagStatics(request);
		return "tag/hello";
	}
    /*
	 * 获取标签编辑
	 */
	@RequestMapping("/getTagFile")
    public String getTagFile(HttpServletRequest request,String file) throws Exception{ 		
    	//模板文件
    	if(file.endsWith("-temp") || file.equals("")){  
    		setTagStatics(request);
    		Random random=new Random();
    		request.setAttribute("random",random.nextInt(9999));
    		if(file.startsWith("lyrow")){       		
        		String[] lyrow;
        		try {
        			lyrow=file.split("-")[1].split("x");
    			} catch (Exception e) {
    				lyrow=new String[]{"12"};
    			}   		
        		request.setAttribute("lyrow", lyrow);
        		return "tag/lyrow-temp";
        	}else if(file.equals("conta-table-temp")){
        		request.setAttribute("pageNumber", 1);
    	        return "tag/"+file;
        	}else{
        		return "tag/"+file;
        	}
    	//编辑模版	
    	}else{
    		if(file.startsWith("lyrow")){       		
        		String lyrow=file.split("-")[1]; 		
        		request.setAttribute("lyrow", lyrow.replaceAll("x", ":"));
        		return "tag/lyrow";
        	}else{
        		return "tag/"+file;
        	}
    	}   	
    }    
	/*
	 * 获取拖动标签列表
	 */
	@ResponseBody
	@RequestMapping("/drag")
	public String drag(TagBean tag,HttpServletResponse response){
		BaseService service=new BaseService("tag");
		service.where("ui=#{ui}");
		if(null==tag.getUi() || "".equals(tag.getUi())){
			tag.setUi("Bootstrap UI");
		}
		service.setData(tag.getUi());
		List<HashMap<String, Object>> list = service.selectList();
		
		StringBuffer bufer=new StringBuffer();
		for(int i=0;i<list.size();i++){
			if(this.intval(list.get(i).get("parentId"))==0){
				String editId=(String) list.get(i).get("tagFile");
				String a="<li id=\"menu-"+editId+"\"><a href=\"javascript:void(0)\" class=\"dropdown-toggle\"><i class=\"menu-icon fa "+list.get(i).get("tagFile")+"\"></i><span class=\"menu-text\">"+list.get(i).get("tagName")+"</span><b class=\"arrow fa fa-angle-down\"></b></a><ul class=\"submenu\">";
				bufer.append(a);
				int tagId=this.intval(list.get(i).get("tagId"));
				for(int m=0;m<list.size();m++){
					int parentId=this.intval(list.get(m).get("parentId"));
					if(parentId==tagId){
						bufer.append("<li><a href=\"javascript:getTagFile('"+list.get(m).get("tempFile")+"','"+list.get(m).get("tagFile")+"',"+list.get(m).get("tagId")+");\"><i class=\"menu-icon fa fa-angle-double-right\"></i><span class=\"menu-text\"> "+list.get(m).get("tagName")+"</span></a></li>");
					}
				}
				String b="</ul></li>";
				bufer.append(b);
			}else{
				continue;
			}
		}
		return bufer.toString();
	}
	
	/*
	 * 打包下载
	 */
	@RequestMapping("/download")
	public void download(String htmlContent,TagBean tag,HttpServletResponse response) throws Exception{
		if(null==htmlContent || "".equals(htmlContent)){
			return;
		}
		BaseService service=App.getService("tag");
		tag = service.selectOne(TagBean.class,tag.getTagId());
		Random rand=new Random();
		int fold=rand.nextInt(999999);
		String path=App.ROOT_PATH + "WEB-INF"+File.separator+"cache"+File.separator+"file"+File.separator+fold;
		htmlContent=writeStaticFile(htmlContent,path,"css");	
		htmlContent=writeStaticFile(htmlContent,path,"js");
		if(tag.getExtraFile()!=null && !tag.getExtraFile().equals("")){
			String[] strs=tag.getExtraFile().split(",");
			for(int i=0;i<strs.length;i++){
				String f1=App.ROOT_PATH+"statics"+File.separator+"tag"+File.separator+strs[i];
				String m="";
				int n=strs[i].lastIndexOf("/");
				if(n!=-1){
					m=strs[i].substring(0,n);
				}
				FileUtils.copyDirectoryToDirectory(new File(f1), new File(path+File.separator+m));
				
			}			
		}		
		FileUtils.writeStringToFile(new File(path+File.separator+"index.html"), htmlContent,"utf-8");
		compressExe(path+File.separator+fold+".zip",path);
		InputStream inStream = new FileInputStream(path+File.separator+fold+".zip");
        response.reset();
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fold+".zip\"");
        byte[] b = new byte[1024];
        int len;
        while ((len = inStream.read(b)) > 0){
        	 response.getOutputStream().write(b, 0, len);
        }
        inStream.close(); 
        deleteDir(new File(path)); 
        service.where("tagId=?").setData(tag.getTagId()).update("download=download+1");
	}
	
	private void setTagStatics(HttpServletRequest request){
		String contextPath = request.getContextPath();
	    String basePath = "";
	    if(request.getServerPort()==80){
	    	basePath = request.getScheme()+"://"+request.getServerName()+contextPath+"/";
	    }else{
	    	basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+contextPath+"/";
	    }		
		request.setAttribute("IMG", basePath+"statics/tag/images/");
		request.setAttribute("CSS", basePath+"statics/tag/css/");
		request.setAttribute("JS", basePath+"statics/tag/js/");
	}
		
	private String writeStaticFile(String htmlContent,String fold,String type){
		if(htmlContent.equals("")){
			return htmlContent;
		}		
		String regex="";
		switch (type) {
		case "css":
			regex="http://.+\\.css";
			fold=fold+File.separator+"css";
			break;
		case "js":
			regex="http://.+\\.js";
			fold=fold+File.separator+"js";
			break;
		default:
			return htmlContent;
		}	
		Pattern start = Pattern.compile(regex);
		Matcher startM = start.matcher(htmlContent);
		boolean result = true; 
		while(result) { 
			result = startM.find(); 
			if(result){
				String url=startM.group(0);
				String filename=url.substring(url.lastIndexOf("/")+1, url.length());
				try {
					URL u=new URL(url);
				    HttpURLConnection conn=(HttpURLConnection)u.openConnection();
				    conn.setConnectTimeout(5000);
				    conn.setRequestMethod("GET");
				    StringBuffer stringBuffer=new StringBuffer();
				    if(conn.getResponseCode()==200){
				        InputStream inputStream=conn.getInputStream();
				        InputStreamReader iReader=new InputStreamReader(inputStream,"utf-8");
				        BufferedReader reader=new BufferedReader(iReader);							       
				        String line="";
				        while ((line=reader.readLine())!=null) {
				        	stringBuffer.append(line+"\n");				
						}
				        inputStream.close();
				    }				
					String str=stringBuffer.toString();
					FileUtils.writeStringToFile(new File(fold+File.separator+filename), str,"utf-8");
					switch (type) {
					case "css":
						htmlContent=htmlContent.replaceFirst(regex, "css/"+filename);
						break;
					case "js":
						htmlContent=htmlContent.replaceFirst(regex, "js/"+filename);
						break;
					default:
						break;
					}										
				} catch (Exception e) {
					continue;
				} 	
			}		
		} 
		return htmlContent;
	}
	
    private boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }
	private void compressExe(String zipFile, String dir) {    
		Zip zip = new Zip();  
	    zip.setBasedir(new File(dir));  
	    zip.setDestFile(new File(zipFile));  
	    Project p = new Project();   
	    zip.setProject(p);  
	    zip.execute();     
    }    
	private <T> int intval(T data){
		if (data instanceof Integer){
			int i=(int) data;
			return i;
		}else{
			try {
				return Integer.valueOf(data.toString());
			} catch (Exception e) {
				return 0;
			}	
		}				
	}	
}